const variableModel = require('../models/variableModel');
const eventModel = require('../models/eventModel');

// 获取全局变量列表
async function getGlobalVariables(req, res, next) {
  try {
    const variables = await variableModel.getGlobalVariables();
    res.json(variables);
  } catch (error) {
    next(error);
  }
}

// 创建或更新全局变量
async function saveGlobalVariable(req, res, next) {
  try {
    const variableData = req.body;
    
    // 基本验证
    if (!variableData.name || !variableData.type) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段'
      });
    }
    
    // 变量名称格式验证
    if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(variableData.name)) {
      return res.status(400).json({
        success: false,
        message: '变量名称格式不正确，只能包含字母、数字和下划线，且必须以字母或下划线开头'
      });
    }
    
    const variable = await variableModel.saveGlobalVariable(variableData);
    res.json(variable);
  } catch (error) {
    next(error);
  }
}

// 删除全局变量
async function deleteGlobalVariable(req, res, next) {
  try {
    const { id } = req.params;
    const result = await variableModel.deleteGlobalVariable(id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '变量不存在'
      });
    }
    
    res.json({
      success: true,
      message: '变量删除成功'
    });
  } catch (error) {
    next(error);
  }
}

// 获取事件局部变量列表
async function getEventVariables(req, res, next) {
  try {
    const { eventId } = req.params;
    
    // 检查事件是否存在
    const event = await eventModel.getEventById(eventId);
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    const variables = await variableModel.getEventVariables(eventId);
    res.json(variables);
  } catch (error) {
    next(error);
  }
}

// 创建或更新事件局部变量
async function saveEventVariable(req, res, next) {
  try {
    const { eventId } = req.params;
    const variableData = req.body;
    
    // 基本验证
    if (!variableData.name || !variableData.type) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段'
      });
    }
    
    // 变量名称格式验证
    if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(variableData.name)) {
      return res.status(400).json({
        success: false,
        message: '变量名称格式不正确，只能包含字母、数字和下划线，且必须以字母或下划线开头'
      });
    }
    
    // 检查事件是否存在
    const event = await eventModel.getEventById(eventId);
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    const variable = await variableModel.saveEventVariable(eventId, variableData);
    res.json(variable);
  } catch (error) {
    next(error);
  }
}

// 删除事件局部变量
async function deleteEventVariable(req, res, next) {
  try {
    const { eventId, id } = req.params;
    
    // 检查事件是否存在
    const event = await eventModel.getEventById(eventId);
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    const result = await variableModel.deleteEventVariable(eventId, id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '变量不存在'
      });
    }
    
    res.json({
      success: true,
      message: '变量删除成功'
    });
  } catch (error) {
    next(error);
  }
}

// 清空事件局部变量
async function clearEventVariables(req, res, next) {
  try {
    const { eventId } = req.params;
    
    // 检查事件是否存在
    const event = await eventModel.getEventById(eventId);
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    await variableModel.clearEventVariables(eventId);
    
    res.json({
      success: true,
      message: `事件 "${event.name}" 的变量已清空`
    });
  } catch (error) {
    next(error);
  }
}

// 获取事件所有可用变量（包括全局变量和局部变量）
async function getAllVariablesForEvent(req, res, next) {
  try {
    const { eventId } = req.params;
    
    // 检查事件是否存在
    const event = await eventModel.getEventById(eventId);
    if (!event) {
      return res.status(404).json({
        success: false,
        message: '事件不存在'
      });
    }
    
    const variables = await variableModel.getAllVariablesForEvent(eventId);
    res.json(variables);
  } catch (error) {
    next(error);
  }
}

// 获取变量被哪些事件使用
async function getVariableUsage(req, res, next) {
  try {
    const { variableType, variableId } = req.params;
    const { page = 1, pageSize = 10 } = req.query;
    
    const pageNum = parseInt(page);
    const size = parseInt(pageSize);
    
    const result = await variableModel.findEventsUsingVariable(variableId, variableType, pageNum, size);
    res.json(result);
  } catch (error) {
    next(error);
  }
}

module.exports = {
  getGlobalVariables,
  saveGlobalVariable,
  deleteGlobalVariable,
  getEventVariables,
  saveEventVariable,
  deleteEventVariable,
  clearEventVariables,
  getAllVariablesForEvent,
  getVariableUsage
}; 